#pragma once
#include <pthread.h>
#include <functional>
#include "socket.hpp"
#include "InetAddr.hpp"
using namespace socket_ns;
using Service_t = std::function<std::string(std::string&)>;
class TcpServer
{
public:
    TcpServer(Service_t Service, u_int16_t port)
        : _Service(Service),
         _port(port),
         _isrunning(false),
         _listenSocket(std::make_shared<TcpSocket>())
    {
        _listenSocket->BuildListenSocket(port);
    }
    ~TcpServer()
    {}
    class ThreadData
    {
    public:
        SockSPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;

    public:
        ThreadData(SockSPtr sockfd, TcpServer *self, const InetAddr &addr) : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }
    };

    static void *Execute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        std::string requeststr;
        int n=td->_sockfd->Recv(&requeststr);
        if(n>0)
        {
            std::string responsestr = td->_self->_Service(requeststr);
            td->_sockfd->Send(responsestr);
        }
        td->_sockfd->Close();
        delete td;
        return nullptr;
    }

    void Run()
    {
        _isrunning=true;
        while (_isrunning)
        {
            InetAddr client;
            SockSPtr newsock = _listenSocket->Accepter(&client);
            if (newsock == nullptr)
                continue;
            LOG(INFO, "get a new link client:%s sockfd:%d\n", client.AddrStr().c_str(), newsock->Sockfd());

            pthread_t tid;
            ThreadData *td = new ThreadData(newsock, this, client);
            pthread_create(&tid, nullptr, Execute, td);
        }
        _isrunning = false;
    }

private:
    Service_t _Service;
    u_int16_t _port;
    bool _isrunning;
    SockSPtr _listenSocket;
};